﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "devinterfacedialog.h"
#include "globalsettings.h"
#include "fcmiddleware.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initUI();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initUI()
{
    ui->hPlot->yAxis->setLabel(QStringLiteral("高速通道"));
    ui->hPlot->xAxis->setLabel(QStringLiteral("时间"));
    ui->lPlot->yAxis->setLabel(QStringLiteral("低速通道"));
    ui->lPlot->xAxis->setLabel(QStringLiteral("时间"));

    GlobalSettings::initChartStyle(ui->hPlot);
    GlobalSettings::initChartStyle(ui->lPlot);

    initHCurve();
    initLCurve();

    ui->hCh1CheckBox->setChecked(true);
    ui->hCh2CheckBox->setChecked(true);
    ui->hCh3CheckBox->setChecked(true);
    ui->hCh4CheckBox->setChecked(true);
    ui->hCh5CheckBox->setChecked(true);
    ui->hCh6CheckBox->setChecked(true);
    ui->hCh7CheckBox->setChecked(true);
    ui->hCh8CheckBox->setChecked(true);

    ui->lCh1CheckBox->setChecked(true);
    ui->lCh2CheckBox->setChecked(true);
    ui->lCh3CheckBox->setChecked(true);
    ui->lCh4CheckBox->setChecked(true);
    ui->lCh5CheckBox->setChecked(true);
    ui->lCh6CheckBox->setChecked(true);
    ui->lCh7CheckBox->setChecked(true);
    ui->lCh8CheckBox->setChecked(true);
    ui->lCh9CheckBox->setChecked(true);
    ui->lCh10CheckBox->setChecked(true);
    ui->lCh11CheckBox->setChecked(true);
    ui->lCh12CheckBox->setChecked(true);
    ui->lCh13CheckBox->setChecked(true);
    ui->lCh14CheckBox->setChecked(true);
    ui->lCh15CheckBox->setChecked(true);
    ui->lCh16CheckBox->setChecked(true);
}

void MainWindow::initHCurve()
{
    for(unsigned int i=0;i<GlobalSettings::SAMPLE_HCHANNEL_SUM;i++)
    {
        _hchannelCurve[i] = new QCPCurve(ui->hPlot->xAxis, ui->hPlot->yAxis);
        _hchannelCurve[i]->setName(QString("CH%1").arg(i+1));
        _hchannelCurve[i]->setVisible(true);
        GlobalSettings::initCurveColor(_hchannelCurve[i], i);
    }
}

void MainWindow::initLCurve()
{
    for(unsigned int i=0;i<GlobalSettings::SAMPLE_LCHANNEL_SUM;i++)
    {
        _lchannelCurve[i] = new QCPCurve(ui->lPlot->xAxis, ui->lPlot->yAxis);
        _lchannelCurve[i]->setName(QString("CH%1").arg(i+1));
        _lchannelCurve[i]->setVisible(true);
        GlobalSettings::initCurveColor(_lchannelCurve[i], i);
    }
}

void MainWindow::on_hCh1CheckBox_stateChanged(int state)
{
    _hchannelCurve[0]->setVisible(state == Qt::Checked);
    ui->hPlot->rescaleAxes(true);
    ui->hPlot->replot();
}

void MainWindow::on_hCh2CheckBox_stateChanged(int state)
{
    _hchannelCurve[1]->setVisible(state == Qt::Checked);
    ui->hPlot->rescaleAxes(true);
    ui->hPlot->replot();
}

void MainWindow::on_hCh3CheckBox_stateChanged(int state)
{
    _hchannelCurve[2]->setVisible(state == Qt::Checked);
    ui->hPlot->rescaleAxes(true);
    ui->hPlot->replot();
}

void MainWindow::on_hCh4CheckBox_stateChanged(int state)
{
    _hchannelCurve[3]->setVisible(state == Qt::Checked);
    ui->hPlot->rescaleAxes(true);
    ui->hPlot->replot();
}

void MainWindow::on_hCh5CheckBox_stateChanged(int state)
{
    _hchannelCurve[4]->setVisible(state == Qt::Checked);
    ui->hPlot->rescaleAxes(true);
    ui->hPlot->replot();
}

void MainWindow::on_hCh6CheckBox_stateChanged(int state)
{
    _hchannelCurve[5]->setVisible(state == Qt::Checked);
    ui->hPlot->rescaleAxes(true);
    ui->hPlot->replot();
}

void MainWindow::on_hCh7CheckBox_stateChanged(int state)
{
    _hchannelCurve[6]->setVisible(state == Qt::Checked);
    ui->hPlot->rescaleAxes(true);
    ui->hPlot->replot();
}

void MainWindow::on_hCh8CheckBox_stateChanged(int state)
{
    _hchannelCurve[7]->setVisible(state == Qt::Checked);
    ui->hPlot->rescaleAxes(true);
    ui->hPlot->replot();
}

void MainWindow::on_lCh1CheckBox_stateChanged(int state)
{
    _lchannelCurve[0]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh2CheckBox_stateChanged(int state)
{
    _lchannelCurve[1]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh3CheckBox_stateChanged(int state)
{
    _lchannelCurve[2]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh4CheckBox_stateChanged(int state)
{
    _lchannelCurve[3]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh5CheckBox_stateChanged(int state)
{
    _lchannelCurve[4]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh6CheckBox_stateChanged(int state)
{
    _lchannelCurve[5]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh7CheckBox_stateChanged(int state)
{
    _lchannelCurve[6]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh8CheckBox_stateChanged(int state)
{
    _lchannelCurve[7]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh9CheckBox_stateChanged(int state)
{
    _lchannelCurve[8]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh10CheckBox_stateChanged(int state)
{
    _lchannelCurve[9]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh11CheckBox_stateChanged(int state)
{
    _lchannelCurve[10]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh12CheckBox_stateChanged(int state)
{
    _lchannelCurve[11]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh13CheckBox_stateChanged(int state)
{
    _lchannelCurve[12]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh14CheckBox_stateChanged(int state)
{
    _lchannelCurve[13]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh15CheckBox_stateChanged(int state)
{
    _lchannelCurve[14]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_lCh16CheckBox_stateChanged(int state)
{
    _lchannelCurve[15]->setVisible(state == Qt::Checked);
    ui->lPlot->rescaleAxes(true);
    ui->lPlot->replot();
}

void MainWindow::on_devInterfaceAction_triggered()
{
    DevInterfaceDialog devInterfaceDialog(this);
    devInterfaceDialog.exec();
}

void MainWindow::on_devConnectAction_triggered()
{
   GlobalSettings::instance()->_frameMgr = new FrameMgr();
   GlobalSettings::instance()->_tcpClientThread =
       new MyTcpClientThread(GlobalSettings::instance()->_frameMgr,
                             GlobalSettings::instance()->_serverIP,
                             GlobalSettings::instance()->_serverPort);
   connect(GlobalSettings::instance()->_tcpClientThread,
           SIGNAL(stateChanged(unsigned int, int, int)),
           this,
           SLOT(stateChanged(unsigned int, int, int)));
   connect(GlobalSettings::instance()->_tcpClientThread,
           SIGNAL(ackReady(void*)),
           this,
           SLOT(ackReady(void*)));
   GlobalSettings::instance()->_tcpClientThread->startServer();
}

void MainWindow::on_devDisconnAction_triggered()
{
    GlobalSettings::instance()->_tcpClientThread->stopServer();
}

void MainWindow::on_singleOpenCapAction_triggered()
{
    IGBTProtocol::SingleCapCmdFrame* singleCapCmdFrame = new IGBTProtocol::SingleCapCmdFrame(IGBTProtocol::Cmd_SingleOpenCap, 200);
    GlobalSettings::instance()->_frameMgr->appendFrame(singleCapCmdFrame);

    GlobalSettings::instance()->clearSamples();
    clearPlot();
}

void MainWindow::on_singleShutupCapAction_triggered()
{
    IGBTProtocol::SingleCapCmdFrame* singleCapCmdFrame = new IGBTProtocol::SingleCapCmdFrame(IGBTProtocol::Cmd_SingleCloseCap, 200);
    GlobalSettings::instance()->_frameMgr->appendFrame(singleCapCmdFrame);

    GlobalSettings::instance()->clearSamples();
    clearPlot();
}

void MainWindow::on_replayCapAction_triggered()
{
    IGBTProtocol::ReplayCapCmdFrame* replayCapCmdFrame = new IGBTProtocol::ReplayCapCmdFrame(200, 300);
    GlobalSettings::instance()->_frameMgr->appendFrame(replayCapCmdFrame);

    GlobalSettings::instance()->clearSamples();
    clearPlot();
}

void MainWindow::on_stopCapAction_triggered()
{
    IGBTProtocol::CmdFrame* stopCapCmdFrame = new IGBTProtocol::CmdFrame(IGBTProtocol::Cmd_StopCap, 5);
    GlobalSettings::instance()->_frameMgr->appendFrame(stopCapCmdFrame);
}

void MainWindow::stateChanged(unsigned int state, int err, int extra)
{
    if (state == FCMiddleware::ThreadStateType_Running)
    {
        logOut(QtInfoMsg, QStringLiteral("TCP线程启动运行..."));
    }
    else if (state == FCMiddleware::ThreadStateType_Opening)
    {
        logOut(QtInfoMsg, QStringLiteral("正在连接TCP服务器..."));
    }
    else if (state == FCMiddleware::ThreadStateType_Reopening)
    {
        logOut(QtInfoMsg, QStringLiteral("正在重新连接TCP服务器..."));
    }
    else if (state == FCMiddleware::ThreadStateType_OpenFailed)
    {
        logOut(QtCriticalMsg, QStringLiteral("连接TCP服务器失败！"));
    }
    else if (state == FCMiddleware::ThreadStateType_Opened)
    {
        logOut(QtInfoMsg, QStringLiteral("连接TCP服务器成功！"));
    }
    else if (state == FCMiddleware::ThreadStateType_WriteFailed)
    {
        logOut(QtCriticalMsg, QStringLiteral("TCP客户端发送数据失败，错误码=") +
                                  QString::number(err) +
                                  QStringLiteral("，命令:") +
                                  IGBTProtocol::cmdTypeCaption((IGBTProtocol::CmdType)extra));
    }
    else if (state == FCMiddleware::ThreadStateType_ReadFailed)
    {
        logOut(QtCriticalMsg, QStringLiteral("TCP客户端接收数据失败，错误码=") +
                                  QString::number(err) +
                                  QStringLiteral("，命令:") +
                                  IGBTProtocol::cmdTypeCaption((IGBTProtocol::CmdType)extra));
    }
    else if (state == FCMiddleware::ThreadStateType_Close)
    {
        logOut(QtWarningMsg, QStringLiteral("TCP连接关闭！"));
    }
    else if (state == FCMiddleware::ThreadStateType_Quit)
    {
        logOut(QtWarningMsg, QStringLiteral("TCP线程退出！"));

        delete GlobalSettings::instance()->_tcpClientThread;
        delete GlobalSettings::instance()->_frameMgr;
        GlobalSettings::instance()->_tcpClientThread = NULL;
        GlobalSettings::instance()->_frameMgr = NULL;
    }
    else if (state == FCMiddleware::ThreadStateType_Quit + 1)
        logOut(QtInfoMsg, QStringLiteral("TCP客户端发送数据成功，命令:") + IGBTProtocol::cmdTypeCaption((IGBTProtocol::CmdType)extra) + QStringLiteral("。"));
}

void MainWindow::ackReady(void* frame)
{
    IGBTProtocol::BaseFrame* recv = (IGBTProtocol::BaseFrame*)frame;
    if(recv->frameHeader() == IGBTProtocol::FrameHeader_Data)
    {
        IGBTProtocol::DataFrame* dataFrame = (IGBTProtocol::DataFrame*)frame;
        if(dataFrame->dataChannel() == IGBTProtocol::DataChannel_HRate)
        {
            depackHChannelSampleData(dataFrame);
            updateHChannelPlot();

            logOut(QtInfoMsg, QStringLiteral("采集到高速通道数据，长度") + QString::number(dataFrame->dataByteSum()) + QStringLiteral("字节。"));
        }
        else if(dataFrame->dataChannel() == IGBTProtocol::DataChannel_LRate)
        {
            depackLChannelSampleData(dataFrame);
            updateLChannelPlot();

            logOut(QtInfoMsg, QStringLiteral("采集到低速通道数据，长度") + QString::number(dataFrame->dataByteSum()) + QStringLiteral("字节。"));
        }
    }
    else if(recv->frameHeader() == IGBTProtocol::FrameHeader_Cmd)
    {
        IGBTProtocol::CmdAckFrame* cmdAckFrame = (IGBTProtocol::CmdAckFrame*)frame;
        QString temp = IGBTProtocol::cmdTypeCaption(cmdAckFrame->execCmdType()) + QStringLiteral("(序号：") + QString::number(cmdAckFrame->execCmdCount()) + ")";
        temp += IGBTProtocol::cmdExecResCaption(cmdAckFrame->execCmdRes());
        if(cmdAckFrame->execCmdType() == IGBTProtocol::Cmd_FaultCap && cmdAckFrame->execCmdRes() == IGBTProtocol::CmdExecRes_Running)
        {
            temp += QStringLiteral("...");
            logOut(QtWarningMsg, temp);
        }
        else if(cmdAckFrame->execCmdRes() == IGBTProtocol::CmdExecRes_Failed)
        {
            temp += QStringLiteral(",错误码:") + QString::number(cmdAckFrame->errCode()) + QStringLiteral("！");
            logOut(QtCriticalMsg, temp);
        }
        else if(cmdAckFrame->execCmdRes() == IGBTProtocol::CmdExecRes_Running)
        {
            temp += QStringLiteral("...");
            logOut(QtInfoMsg, temp);
        }
        else
        {
            temp += QStringLiteral("。");
            logOut(QtInfoMsg, temp);
        }
    }

    delete frame;
}

void MainWindow::logOut(QtMsgType type, const QString msg)
{
    static unsigned int lineCount = 0;

    if (lineCount > 2000)
    {
        ui->textEdit->clear();
        lineCount = 0;
    }

    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit->setTextCursor(cursor);

    switch (type)
    {
    case QtInfoMsg:
        ui->textEdit->setTextColor(Qt::black);
        break;
    case QtWarningMsg:
        ui->textEdit->setTextColor(Qt::blue);
        break;
    case QtDebugMsg:
        ui->textEdit->setTextColor(Qt::cyan);
        break;
    case QtCriticalMsg:
        ui->textEdit->setTextColor(Qt::red);
        break;
    case QtFatalMsg:
        ui->textEdit->setTextColor(Qt::red);
        break;
    }

    QString strDtMsg = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    ui->textEdit->insertPlainText(strDtMsg + " " + msg + "\n");

    lineCount++;
}

void MainWindow::depackHChannelSampleData(IGBTProtocol::DataFrame* dataFrame)
{
    unsigned short channelSamples = dataFrame->channelSampleNum(GlobalSettings::SAMPLE_HCHANNEL_SUM,GlobalSettings::BYTES_PER_HCHANNEL_SAMPLE);
    const unsigned char* data = dataFrame->data();
    for(unsigned int i=0;i<channelSamples;i++)
        GlobalSettings::instance()->appendHChannelSample(data+i*GlobalSettings::SAMPLE_HCHANNEL_SUM*GlobalSettings::BYTES_PER_HCHANNEL_SAMPLE);
}

void MainWindow::updateHChannelPlot(/*int channelSampleNum*/)
{
    unsigned int index;
    const QVector<GlobalSettings::PTR_HSamplePacket>* samples = GlobalSettings::instance()->hchannelSamples();

    QVector<QCPCurveData> data(samples->count());
    QVector<GlobalSettings::PTR_HSamplePacket>::const_iterator it;

    for(unsigned int i=0;i<GlobalSettings::SAMPLE_HCHANNEL_SUM;i++)
    {
        it = samples->begin();
        index = 0;
        while(it != samples->end())
        {
            data[index] = QCPCurveData(index, 0.00000002 * (double)index, (*it)->_sample[i]);

            it++;
            index++;
        }

        _hchannelCurve[i]->data()->set(data,true);
        //_hchannelCurve[i]->setVisible(true);
    }

    ui->hPlot->rescaleAxes();
    ui->hPlot->replot();
}

void MainWindow::depackLChannelSampleData(IGBTProtocol::DataFrame* dataFrame)
{
    unsigned short channelSamples = dataFrame->channelSampleNum(GlobalSettings::SAMPLE_LCHANNEL_SUM,GlobalSettings::BYTES_PER_LCHANNEL_SAMPLE);
    const unsigned char* data = dataFrame->data();
    for(unsigned int i=0;i<channelSamples;i++)
        GlobalSettings::instance()->appendLChannelSample(data+i*GlobalSettings::SAMPLE_LCHANNEL_SUM*GlobalSettings::BYTES_PER_LCHANNEL_SAMPLE);
}

void MainWindow::updateLChannelPlot(/*int channelSampleNum = -1*/)
{
    unsigned int index;
    const QVector<GlobalSettings::PTR_LSamplePacket>* samples = GlobalSettings::instance()->lchannelSamples();

    QVector<QCPCurveData> data(samples->count());
    QVector<GlobalSettings::PTR_LSamplePacket>::const_iterator it;

    for(unsigned int i=0;i<GlobalSettings::SAMPLE_LCHANNEL_SUM;i++)
    {
        it = samples->begin();
        index = 0;
        while(it != samples->end())
        {
            data[index] = QCPCurveData(index, 0.00005 * (double)index, (*it)->_sample[i]);

            it++;
            index++;
        }

        _lchannelCurve[i]->data()->set(data,true);
        //_lchannelCurve[i]->setVisible(true);
    }

    ui->lPlot->rescaleAxes();
    ui->lPlot->replot();
}

void MainWindow::clearPlot()
{
    for(unsigned int i=0;i<GlobalSettings::SAMPLE_HCHANNEL_SUM;i++)
    {
        _hchannelCurve[i]->data()->clear();
        //_hchannelCurve[i]->setVisible(false);
    }

    for(unsigned int i=0;i<GlobalSettings::SAMPLE_LCHANNEL_SUM;i++)
    {
        _lchannelCurve[i]->data()->clear();
        //_lchannelCurve[i]->setVisible(false);
    }

    ui->hPlot->replot();
    ui->lPlot->replot();
}
